package com.group.activity.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.group.activity.entity.PuzzleListEntity;
import com.group.activity.entity.ShopUserEntity;
import com.group.activity.service.PuzzleListService;
import com.group.common.utils.*;
import com.group.common.vo.ShopUserVo;
import com.sun.media.jfxmedia.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.group.activity.dao.GroupPeoplerecordDao;
import com.group.activity.entity.GroupPeoplerecordEntity;
import com.group.activity.service.GroupPeoplerecordService;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;


@Slf4j
@Service("groupPeoplerecordService")
public class GroupPeoplerecordServiceImpl extends ServiceImpl<GroupPeoplerecordDao, GroupPeoplerecordEntity> implements GroupPeoplerecordService {


    @Autowired
    PuzzleListService puzzleListService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    SymmetricEncoder symmetricEncoder;

    @Override
    public R joinGroupbuy(GroupPeoplerecordEntity groupPeoplerecordEntity, HttpSession session) {
        //分布式锁
        String groupShopId = redisTemplate.opsForValue().get("groupShopId");
        //打印日志
        log.info(groupShopId);
        //转换类型
        int i = Integer.parseInt(groupShopId);
        RLock lock = redissonClient.getLock("groupbuy-lock" + groupShopId);
        boolean islock;
        try {
            islock=lock.tryLock(3,10, TimeUnit.SECONDS);
            if (!islock)return R.error("系统繁忙,请稍后重试");
            //根据商品id去查拼团得状态信息
            PuzzleListEntity puzzleListEntity = puzzleListService.getOne(new QueryWrapper<PuzzleListEntity>().eq("puzzle_list_id",i));
            //打印日志
            log.info(puzzleListEntity.toString());
            //判断活动信息
            if (puzzleListEntity==null)return R.error("拼团数据获取有误,无法加入");
            Integer groupStatus = puzzleListEntity.getGroupStatus();
            //打印日志
            log.info(String.valueOf(groupStatus));
            //判断活动状态
            if (puzzleListEntity.getGroupStatus()==1)return R.error("拼团已经关闭，无法加入");
            Date endTime = puzzleListEntity.getEndTime();
            //打印日志
            log.info(String.valueOf(endTime));
            //判断活动时间
            if (puzzleListEntity.getEndTime().compareTo(new Date())<0)return R.error("时间已经过期,无法加入");
            //判断活动人数
            if (puzzleListEntity.getGroupCount()>=puzzleListEntity.getGroupMaxcount())return R.error("人数满了，无法加入");
            /*
            根据session获取当前登录信息
            */
            Object userlogin = session.getAttribute("loginUser");
            //打印日志
            log.info(userlogin.toString());
            //类型转换 json
            String s = JSON.toJSONString(userlogin);
            ShopUserVo shopUserEntity = JSON.parseObject(s, new TypeReference<ShopUserVo>() {
            });
            //打印
            log.info(shopUserEntity.toString());
            //获取当前登录人的id
            Integer userId = shopUserEntity.getUserId();
            //打印日志
            log.info(String.valueOf(userId));
            //根据当前登陆人的id去查询数据库有没有这个id
            Integer groupId =baseMapper.selectuserid(userId,i);
            //判断用户是否重复
            if (groupId!=null)return R.error("已加入，请勿重复加入");
            //递增人数
            puzzleListService.updateid(i);
            //获取活动名称
            String userName = shopUserEntity.getUserName();
            //赋值用户id
            groupPeoplerecordEntity.setGroupUserId(userId);
            //赋值用户名称
            groupPeoplerecordEntity.setGroupUserName(userName);
            //赋值活动id
            groupPeoplerecordEntity.setGroupShopId(i);
            //获取活动名称
            String groupName = puzzleListEntity.getGroupName();
            //赋值活动名称
            groupPeoplerecordEntity.setGroupShopName(groupName);
            //新增记录信息
            baseMapper.insert(groupPeoplerecordEntity);
            //加入成功 打印信息
            return R.ok("加入成功").put("data",groupPeoplerecordEntity);
        } catch (Exception e) {
            log.error(e.getMessage());
        }finally {
            //解锁
            lock.unlock();
        }
        //加入失败 打印error
        return R.error("加入失败");
    }

    @Override
    public List<GroupPeoplerecordEntity> groupShopList(Integer groupShopid) {
        return baseMapper.groupShopList(groupShopid);
    }

    @Override
    public R generatelinl(String aesone, String aestwo, ShopUserVo user,GroupPeoplerecordEntity groupPeoplerecordEntity) {
        //解密
        String groupshopid = symmetricEncoder.AESDncode("DES", aesone);
        String useId = symmetricEncoder.AESDncode("DES", aestwo);
        //类型转换
        Integer shopid = Integer.parseInt(groupshopid);
        Integer i = Integer.parseInt(useId);
        //用户是否登录
        if (user == null) {
            return R.error("登录后才能帮好友进行拼团呦");
        }
        //分布式锁
        RLock lock = redissonClient.getLock("groupbuy-lock"+groupshopid);
        boolean islock;
        try {
            //锁时间
            islock=lock.tryLock(3,10, TimeUnit.SECONDS);
            //判断是否获取锁
            if (!islock)return R.error("系统繁忙,请稍后重试");
            if (shopid == null || i == null) {
                return R.ok("访问地址不存在");
            }
            //根据商品id去查拼团得状态信息
            PuzzleListEntity puzzleListEntity = puzzleListService.getOne(new QueryWrapper<PuzzleListEntity>().eq("puzzle_list_id",shopid));
            //判断拼团信息
            if (puzzleListEntity==null)return R.error("拼团数据获取有误,无法加入");
            //获取拼团状态
            Integer groupStatus = puzzleListEntity.getGroupStatus();
            //判断活动状态信息
            if (puzzleListEntity.getGroupStatus()==1)return R.error("拼团已经关闭，无法加入");
            //获取结束时间
            Date endTime = puzzleListEntity.getEndTime();
            //打印日志
            log.info(String.valueOf(endTime));
            //判断活动时间是否过期
            if (puzzleListEntity.getEndTime().compareTo(new Date())<0)return R.error("时间已经过期,无法加入");
            //判断人数是否满了
            if (puzzleListEntity.getGroupCount()>=puzzleListEntity.getGroupMaxcount())return R.error("人数满了，无法加入");
            //获取当前登录人id
            Integer userId = user.getUserId();
            //查询记录表信息
            Integer groupId =baseMapper.selectuserid(userId,shopid);
            //判断用户是否重复加入
            if (groupId!=null)return R.error("已加入，请勿重复加入");
            //递增人数
            puzzleListService.updateshopid(shopid);
            //获取当前用户名称
            String userName = user.getUserName();
            //赋值用户id
            groupPeoplerecordEntity.setGroupUserId(userId);
            //赋值用户名称
            groupPeoplerecordEntity.setGroupUserName(userName);
            //赋值活动id
            groupPeoplerecordEntity.setGroupShopId(shopid);
            //获取活动名称
            String groupName = puzzleListEntity.getGroupName();
            //赋值活动名称
            groupPeoplerecordEntity.setGroupShopName(groupName);
            //新增记录信息
            baseMapper.insert(groupPeoplerecordEntity);
            //加入成功 打印信息
            return R.ok("加入成功").put("data",groupPeoplerecordEntity);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //加入失败 打印error
        return R.error("加入失败");
    }


}